package edu.nf.ch07.container;

import io.github.classgraph.ClassInfo;
import io.github.classgraph.ClassInfoList;

import java.util.HashMap;
import java.util.Map;

/**
 * @author CSY
 * @date 2025 - 04 - 16
 * 容器工厂
 */
public class ContainerFactory {
    /**
     * 容器 - 用于存放带有@component注解的类实例
     */
    private final Map<String,Object> container = new HashMap<>();

    /**
     * 初始化字段注入处理器
     */
    private final FieldInjectHandler injectHandler = new FieldInjectHandler();

    /**
     * 初始化工厂
     * @param packageName 包名
     */
    public ContainerFactory(String packageName) {
        //初始化
        init(packageName);
        processInject();
    }

    /**
     * 给所有的Bean执行注入装配
     */
    private void processInject(){
        for (String key : container.keySet()) {
            Object instance = container.get(key);
            //执行对象的注入装配
            injectHandler.handle(instance,this);
        }
    }

    private void init(String packageName) {
        //执行扫描
        ClassInfoList list = ScanUtils.scan(packageName);
        //循环遍历集合中的类，找出带有@Compontent注解的类
        for (ClassInfo classInfo : list) {
            Class<?> clazz = classInfo.loadClass();
            if (clazz.isAnnotationPresent(Component.class)){
                try {
                    //将带有注解的类实例存放到容器中
                    Component component = clazz.getAnnotation(Component.class);
                    String name = component.value();
                    Object instance = clazz.getConstructor().newInstance();
                    //将数据保存到容器中
                    container.put(name,instance);
                } catch (Exception e) {
                    throw new RuntimeException("New instance fail."+e);
                }
            }
        }
    }

    /**
     * 根据名称从容器中获取对象
     * @param name 容器中的key
     * @return 对应的实力
     * @param <T>
     */
    public <T> T getBean (String name){
        if (container.containsKey(name)){
            return (T)container.get(name);
        }
        throw new RuntimeException("No such bean: "+name);
    }
}
